package com.drugmanage.service.impl;

import com.drugmanage.Base.BaseService;
import com.drugmanage.dao.DrugDao;
import com.drugmanage.dao.SaleDrugDao;
import com.drugmanage.entity.Drug;
import com.drugmanage.entity.SaleDrug;
import com.drugmanage.query.SaleDrugQuery;
import com.drugmanage.service.ISaleDrugService;
import com.drugmanage.utils.AssertUtil;
import com.drugmanage.utils.ValidateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SaleDrugService implements ISaleDrugService {

    @Resource
    private SaleDrugDao saleDrugDao;
    @Resource
    private DrugDao drugDao;

    public void insert(SaleDrug saleDrug) {
        checkParams(saleDrug.getDrugid(), saleDrug.getDrugnum());
        BigDecimal price = drugDao.getByDrugId(saleDrug.getDrugid()).getSaleprice();
        BigDecimal totalPrice = price.multiply(new BigDecimal(saleDrug.getDrugnum()));
        saleDrug.setTotalprice(totalPrice);
        saleDrug.setCreateDate(new Date());
        saleDrug.setUpdateDate(new Date());
        saleDrug.setIsvalid(true);
        drugDao.updateDrugNum(saleDrug.getDrugnum(), saleDrug.getDrugid());
        saleDrugDao.save(saleDrug);
    }

    private void checkParams(Integer drugid, Integer drugnum) {
        AssertUtil.isTure(ValidateUtil.nullOrZeroInteger(drugid), "请输入药品Id");
        Drug drug = drugDao.getByDrugId(drugid);
        AssertUtil.isTure(null == drug || !drug.getIsvalid(), "该药品不存在！");
        AssertUtil.isTure(drug.getDrugnum() <= drugnum, "库存不足！");
        AssertUtil.isTure(ValidateUtil.nullOrZeroInteger(drugnum), "请输入药品数量");
    }

    public void deleteBatch(Integer[] ids) {
        saleDrugDao.deleteBatch(ids);
    }

    @Override
    public Map<String, Object> queryForPage(SaleDrugQuery saleDrugQuery) {
        PageHelper.startPage(saleDrugQuery.getPage(), saleDrugQuery.getRows());
        List<SaleDrug> saleDrugs = saleDrugDao.queryForPage(saleDrugQuery);
        if (!ValidateUtil.blankList(saleDrugs)) {
            for (SaleDrug saleDrug : saleDrugs) {
                Drug drug = drugDao.getDrugByDrugId(saleDrug.getDrugid());
                if (drug != null) {
                    saleDrug.setDrugName(drug.getDrugname());
                }

            }
        }
        PageInfo<SaleDrug> pageInfo = new PageInfo<SaleDrug>(saleDrugs);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("total", pageInfo.getTotal());
        map.put("rows", pageInfo.getList());
        return map;
    }
}
